import {reqCartList,reqDeleteCartById,reqUpdateCheckedById} from '@/api'
const state ={
    CartList: []
}
const mutations ={
    GETCARTLIST(state,res){
        state.CartList = res
    }
}
const actions = {
    // 获取购物车列表数据
    async getCartList ({commit}) {
       let result = await reqCartList()
       if(result.code === 200){
        commit('GETCARTLIST',result.data)
       }
    },
    // 删除购物车的某件商品
    async deleteCart ({commit},skuId){
        let result = await reqDeleteCartById(skuId)
        if(result.code === 200){ 
            return 
        }else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 修改购物车某一产品的选中状态
    async UpdateCheckedById({commit},{skuId,isChecked}){
        let result = await reqUpdateCheckedById(skuId,isChecked)
    },
    // 删除选中商品
    deleteAllChecked({dispatch,getters}){
    // 获取购物车全部商品【是一个数组】
        let PromiseAll = []
        getters.CartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCart',item.skuId) : ''
            // 只要是选中状态，就保存到promiseAll当中
            PromiseAll.push(promise)
        })
        // 只要循环的promise都成功，返回结果为成功 【即dispatch的派发都成功，否则返回失败结果】
        return Promise.all(PromiseAll) 
    },
    // 全选按钮状态
    upDateCheckedAll({state,dispatch},isChecked){
        let promiseAll = []
        state.CartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('UpdateCheckedById',{skuId: item.skuId,isChecked})
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
}
const getters ={
    CartList(state){
        return state.CartList[0] || {}
    }
}
export default{
    state,
    mutations,
    actions,
    getters
}